// [!CPPName] : Implementation of [!ClassName]
[!crlf]

#include "stdafx.h"
#include "[!ProjectName].h"
#include "[!HeaderName]"
[!if=(ScoringComponent, "TRUE")]
#include "SmartDict.h"
[!endif]
[!if=(CacheLoader, "TRUE")]
#include "comp_ids.h"
[!endif]
[!crlf]

/////////////////////////////////////////////////////////////////////////////
// [!ClassName]
[!crlf]

STDMETHODIMP [!ClassName]::InterfaceSupportsErrorInfo(REFIID riid)
{
	static const IID* arr[] = 
	{
		&IID_I[!CoClassName],
	};
	for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
	{
		if (InlineIsEqualGUID(*arr[i],riid))
			return S_OK;
	}
	return S_FALSE;
}
[!crlf]

//
// IPipelineComponent Methods
//

STDMETHODIMP [!ClassName]::Execute (
                IDispatch*  pdispOrder,
                IDispatch*  pdispContext,
                LONG        lFlags,
                LONG*       plErrorLevel)
{
	HRESULT hRes = S_OK;
[!if=(ScoringComponent)]
    CSmartDict  sdOrder;
    CComPtr<IDispatch>      spdispContentList;
    CComPtr<IContentList>   spContentList;
    VARIANT_BOOL            vbTraceMode;
    double                  dtNow;          // days since Jan 1, 1900
[!crlf]
    // get the Content list
    if (FAILED(hRes = sdOrder.Init(pdispOrder, L"Order", L"[!ProgID]")))
        goto HandleError;
    if (FAILED(hRes = sdOrder.GetValue(L"_content", &spdispContentList)))
        goto HandleError;
    if (FAILED(hRes = spdispContentList->QueryInterface(IID_IContentList, (void**)&spContentList)))
        goto HandleError;
[!crlf]
    // see if tracemode is on in the ContentList
    if (FAILED(hRes = spContentList->get_TraceMode(&vbTraceMode)))
        goto HandleError;
[!crlf]
    // get contentlist schema (note this caches for multiple executions)
    if (FAILED(hRes = GET_CL_SCHEMA(spContentList)))
        goto HandleError;
[!crlf]
    // get today's date as VariantTime (days since Jan 1, 1900)
    {
        SYSTEMTIME  st;
        GetSystemTime(&st);
        SystemTimeToVariantTime(&st, &dtNow);
    }
[!crlf]
    if (SUCCEEDED(hRes))
    {
        VARIANT_BOOL    fEOF;           // EndOfRowCollection flag
        CComPtr<IRowCollection> spRows;
[!crlf]
        // get rows that haven't been filtered out by this stage
        if (FAILED(hRes = spContentList->get_ActiveRows(&spRows)))
            goto HandleError;
[!crlf]
        // check for empty
        if (FAILED(hRes = spRows->get_EOF(&fEOF)))
            goto HandleError;
	[!crlf]
[!crlf]
		// TODO: Insert custom scoring logic here.
[!crlf]
    }
[!crlf]
HandleError:
[!else]
[!if=(CacheLoader,"TRUE")]
    CComBSTR	bstrTempTable, 
				bstrDropQuery,
				bstrDictItem,
				bstrNULL;
	CComVariant	varDictValue,
				varRecordsAffected;
    CComQIPtr<ADORecordset>	prsRecordSet;
    CComQIPtr<IDictionary>	pdictOrder, 
							pdictContext, 
							pdictNewDict;
[!crlf]
    CComQIPtr<_ADOConnection> pConn;
	pConn.CoCreateInstance(L"ADODB.Connection");
	ATLASSERT(! (NULL == pConn.p));
[!crlf]
    CComQIPtr<IContentListFactory> pclfFactory;
    CComQIPtr<IPipelineComponent> ppcLoadCampCommon;
	long lErrorLevel;
[!crlf]
	WCHAR szwDropQuery[100];
[!crlf]
	memset(szwDropQuery,0,100 * sizeof(WCHAR));
[!crlf]
	// First, check our parameters to be sure they are valid.
	if ((NULL == plErrorLevel) ||
		(NULL == pdispOrder) ||
		(NULL == pdispContext))
	{
		hRes = E_POINTER;
		goto HANDLE_ERROR;
	}
[!crlf]
	// Initialize to a failure condition.
	*plErrorLevel = PIPECOMP_STATUS_FAIL;
[!crlf]
	// QI for the IDictionary interface on these objects.
    pdictOrder = pdispOrder;
    pdictContext = pdispContext;
[!crlf]
	ATLASSERT(! (NULL == pdictOrder.p));
	ATLASSERT(! (NULL == pdictContext.p));
[!crlf]
	if ((NULL == pdictOrder.p) ||
		(NULL == pdictContext.p))
	{
		hRes = E_POINTER;
		goto HANDLE_ERROR;
	}
[!crlf]
    // Get a unique temp table name (based on a GUID)
    // The Commerce.CSFLoadCampaignsCommon component uses the contents of the
    // temp table to join various tables and form subsequent queries that
    // are used in populating the ContentList
    bstrTempTable = GetGUIDForTableName();
[!crlf]
	ATLASSERT(! (L"" == bstrTempTable));
[!crlf]
    // Ensure a ConnectionString has been configured
    if (L"" == m_bstrConnStr)
	{
		*plErrorLevel = PIPECOMP_STATUS_FAIL;
        hRes = Error(L"CSFLoadHeadlines Error - ConnectionString not set", GUID_NULL,E_FAIL);
		goto HANDLE_ERROR;
    }
[!crlf]
    // open a connection
    if (FAILED(hRes = pConn->Open(m_bstrConnStr,bstrNULL, bstrNULL,0)))
		goto HANDLE_ERROR;
[!crlf]
    // Execute our query and turn the result into a ContentListFactory
    if (FAILED(hRes = CreateFactoryFromQuery(pConn, bstrTempTable, &pclfFactory)))
		goto HANDLE_ERROR;
[!crlf]
	if (NULL == pclfFactory.p)
	{
		hRes = E_UNEXPECTED;
		goto HANDLE_ERROR;
	}
[!crlf]
    // put it in the cache dictionary
	varDictValue.vt = VT_DISPATCH;
	if (FAILED(hRes = pclfFactory->QueryInterface(IID_IDispatch, reinterpret_cast<void**>(&(varDictValue.pdispVal)))))
		goto HANDLE_ERROR;
[!crlf]
	bstrDictItem = L"factory";
    if (FAILED(hRes = pdictOrder->putref_Value(bstrDictItem,varDictValue)))
		goto HANDLE_ERROR;
[!crlf]
	varDictValue.Clear();
[!crlf]
    // This step is useful for integrating with the Campaign Eventing system
    // (RecordEvent pipeline component and WriteEvents cache writer component)
    // These components together will maintain aggregate event counts in the
    // performance_total database table.  Events are recorded in-memory into
    // the _performance dictionary, then written to the DB during cache refresh.
    // Recall that dictContext contains the previous version of the cache, if there
    // was one
	bstrDictItem = L"_performance";
	if (FAILED(hRes = pdictContext->get_Value(bstrDictItem,&varDictValue)))
		goto HANDLE_ERROR;
[!crlf]
    if ((VT_DISPATCH == varDictValue.vt) ||
		(VT_UNKNOWN == varDictValue.vt))
	{
		if (FAILED(hRes = pdictOrder->putref_Value(bstrDictItem,varDictValue)))
			goto HANDLE_ERROR;
    }
	else
	{
		varDictValue.Clear();
		pdictNewDict.CoCreateInstance(L"Commerce.Dictionary");
		varDictValue.vt = VT_DISPATCH;
		if (FAILED(hRes = pdictNewDict->QueryInterface(IID_IDispatch, reinterpret_cast<void**>(&(varDictValue.pdispVal)))))
			goto HANDLE_ERROR;
[!crlf]
		if (FAILED(hRes = pdictOrder->putref_Value(bstrDictItem,varDictValue)))
			goto HANDLE_ERROR;
	}
[!crlf]
    // Now register this CSF app in the virtual_directory table
    if (FAILED(hRes = UpdateVDir(pConn, pdictOrder)))
		goto HANDLE_ERROR;
[!crlf]
    // If you are using expressions and want the expressions automatically refreshed as
    // part of a headline cache refresh, you could configure another property to hold a
    // a reference to the global ExpressionEvaluator object and call its LoadAll or FlushAll
    // method.  This is already done by ads and discounts, so if you are using the same
    // instance of Evaluator, this is already happening periodically in the background, so
    // we won't do that here.
[!crlf]
    // Now we've done our part - let the CSFLoadCampaignsCommon component do the rest
	ppcLoadCampCommon.CoCreateInstance(L"Commerce.CSFLoadCampaignsCommon");
[!crlf]
    // Pass it some stuff through Order dictionary
	varDictValue.Clear();
	varDictValue = m_bstrConnStr;
	bstrDictItem = L"ConnectionString";
	if (FAILED(hRes = pdictOrder->put_Value(bstrDictItem,varDictValue)))
		goto HANDLE_ERROR;
[!crlf]
	varDictValue.Clear();
    varDictValue = bstrTempTable;
	bstrDictItem = L"TempTable";
	if (FAILED(hRes = pdictOrder->put_Value(bstrDictItem,varDictValue)))
		goto HANDLE_ERROR;
[!crlf]
	varDictValue.Clear();
[!crlf]
    // Execute it
    if (FAILED(hRes = ppcLoadCampCommon->Execute(pdictOrder, pdispContext, 0, &lErrorLevel)))
		goto HANDLE_ERROR;
[!crlf]
    // Finally, drop the global temp table
	wsprintf(szwDropQuery,L"Drop table ##%s", bstrTempTable);
	bstrDropQuery = szwDropQuery;
    if (FAILED(hRes = pConn->Execute(bstrDropQuery,&varRecordsAffected, adExecuteNoRecords, &prsRecordSet)))
		goto HANDLE_ERROR;
[!crlf]
	*plErrorLevel = PIPECOMP_STATUS_OK;
[!crlf]
HANDLE_ERROR:
[!else]
[!if=(Shipping,"TRUE")]
	CComQIPtr<IEnumVARIANT, &IID_IEnumVARIANT> pNewEnum;
	VARIANT					varNextItem;
	CComBSTR				bstrName;
	CComBSTR				bstrShippingAddressID;
	CComBSTR				bstrCountry;
[!crlf]
	CComQIPtr<IDictionary>	pdictPipeCtx;
	CComQIPtr<IDictionary>  pdictOrderForm;
	CComQIPtr<ISimpleList>	pslItems;
	CComPtr<IUnknown>		pUnk;
[!crlf]
	CComQIPtr<IDictionary>	pdictShipment;
	CComQIPtr<ISimpleList>	pslShipmentsToProcess;
	CComQIPtr<IDictionary>	pdictAddresses; // Ship-to addresses
	CComQIPtr<IDictionary>	pdictAddress;
[!crlf]
    *plErrorLevel = PIPECOMP_STATUS_OK;
[!crlf]
	VariantInit(&varNextItem);
[!crlf]
	pdictPipeCtx = pdispContext;
	pdictOrderForm = pdispOrder;
	ATLASSERT(NULL != pdictPipeCtx.p);
	ATLASSERT(NULL != pdictOrderForm.p);
	if ((NULL == pdictPipeCtx.p) ||
		(NULL == pdictOrderForm.p))
	{
		hRes = E_FAIL;
		goto HANDLE_ERROR;
	}
[!crlf]
	// Populate the addresses object.
	if (FAILED(hRes = QueryForDictionary(pdictOrderForm,L"Addresses",&pdictAddresses)))
		goto HANDLE_ERROR;
[!crlf]
	// Shipping components iterate over a list of shipments to process
	if (FAILED(hRes = QueryForSimpleList(pdictPipeCtx,L"shipments_to_process",&pslShipmentsToProcess)))
		goto HANDLE_ERROR;
[!crlf]
	// Get the IEnumVARIANT interface pointer so we can walk
	// the items in the list.
	if (FAILED(hRes = pslShipmentsToProcess->get__NewEnum(&pUnk)))
		goto HANDLE_ERROR;
[!crlf]
	pNewEnum = pUnk;
	ATLASSERT(NULL != pNewEnum.p);
	if (NULL == pNewEnum.p)
	{
		hRes = E_FAIL;
		goto HANDLE_ERROR;
	}
[!crlf]
	// This is essentially a VB For Each loop that walks through
	// the list of ShipmentsToProcess.
	while (pNewEnum->Next(1, &varNextItem, NULL) == S_OK)
	{
		if(VT_DISPATCH == varNextItem.vt)
		{
			// Implicit QI for IDictionary.
			pdictShipment = varNextItem.pdispVal;
			ATLASSERT(NULL != pdictShipment.p);
		}
		else
		{
			ATLASSERT(0);
			VariantClear(&varNextItem);
			hRes = E_FAIL;
			break;
		}
		VariantClear(&varNextItem);
[!crlf]
		// Each shipment dictionary contains a shipping_address_id, that refers to the address dict for the shipment
		if (FAILED(hRes = QueryForBSTR(pdictShipment,L"shipping_address_id",&bstrShippingAddressID)))
			goto HANDLE_ERROR;
[!crlf]
		// Get the Address Dictionary.
		if (FAILED(hRes = QueryForDictionary(pdictAddresses, bstrShippingAddressID, &pdictAddress)))
			goto HANDLE_ERROR;
[!crlf]
		// Get some shipment address info (here we get the country of the shipment)
		if (FAILED(hRes = QueryForBSTR(pdictAddress, L"Country", &bstrCountry)))
			goto HANDLE_ERROR;
[!crlf]
		// ***************************************************
		// Your code for handling shipping addresses goes here
		// ***************************************************
[!crlf]
		pdictShipment.Release();
		pdictAddress.Release();
	}
[!crlf]
HANDLE_ERROR:
[!else]
[!crlf]
	// TODO: Add code that performs the main operations for this component
[!crlf]
[!endif]
[!endif]
[!endif]
    return hRes;
}
[!crlf]

STDMETHODIMP [!ClassName]::EnableDesign(BOOL fEnable)
{  
    return S_OK;
}
[!crlf]

[!if=(IPersistStreamInit, "TRUE")]
//
// IPersistStreamInit Methods
//

STDMETHODIMP [!ClassName]::GetClassID(CLSID *pClassID)
{
	*pClassID = GetObjectCLSID();
	return S_OK;
}
[!crlf]

STDMETHODIMP [!ClassName]::IsDirty(void)
{
	return S_OK;
}
[!crlf]

STDMETHODIMP [!ClassName]::Load(IStream *pStm)
{
	HRESULT hRes = S_OK;
	[!crlf]
	// TODO: Add code to load data from the stream
	[!crlf]
	return hRes;
}
[!crlf]

STDMETHODIMP [!ClassName]::Save(IStream *pStm, BOOL fClearDiry)
{

	HRESULT hRes = S_OK;
[!crlf]
	// TODO: Add code to save data to the stream
[!crlf]
	return hRes;
}
[!crlf]

STDMETHODIMP [!ClassName]::GetSizeMax(ULARGE_INTEGER *pcbSize)
{
[!crlf]
	// TODO: Modify size to be the size of your data
[!crlf]
    pcbSize->LowPart  = 0;
	pcbSize->HighPart = 0;	
[!crlf]
	return S_OK;
}
[!crlf]

STDMETHODIMP [!ClassName]::InitNew(void)
{
	// TODO: Add any component initialization
[!crlf]
	return S_OK;
}
[!crlf]
[!endif]


[!if=(IPipelineComponentDescription, "TRUE")]
//
// IPipelineComponentDescription Methods
//

STDMETHODIMP [!ClassName]::ContextValuesRead(VARIANT *pVarRead)
{
[!if=(ScoringComponent, "TRUE")]
    int cEntries = 0;
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
    // set up the return value to point to the safearray
    V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarRead) = psa;
    return S_OK;
[!else]
	// TODO: Add your own values to the array
[!crlf]
	int cEntries = 1;
[!crlf]
	// allocate the safearray of VARIANTs
	SAFEARRAY*	psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
[!crlf]
	// Populate the safearray variants
	VARIANT* pvarT = (VARIANT*)psa->pvData;
	V_BSTR(pvarT) = SysAllocString(L"Example Context Value Read");
	V_VT(pvarT) = VT_BSTR;
[!crlf]
	// set up the return value to point to the safearray
	V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
	V_ARRAY(pVarRead) = psa;
[!crlf]
	return S_OK;
[!endif]
}
[!crlf]

STDMETHODIMP [!ClassName]::ValuesRead(VARIANT *pVarRead)
{
[!if=(ScoringComponent,"TRUE")]
    int cEntries = 2;
[!crlf]
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
[!crlf]
    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"_content.headline_date");
    V_VT(pvarT) = VT_BSTR;
[!crlf]
    pvarT++;
    V_BSTR(pvarT) = SysAllocString(L"_content.headline_priority");
    V_VT(pvarT) = VT_BSTR;
[!crlf]
    // set up the return value to point to the safearray
    V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarRead) = psa;
[!crlf]
    return S_OK;
[!else]
	// TODO: Add your own values to the array
[!crlf]
	int cEntries = 1;
[!crlf]
	// allocate the safearray of VARIANTs
	SAFEARRAY*	psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
[!crlf]
	// Populate the safearray variants
	VARIANT* pvarT = (VARIANT*)psa->pvData;
	V_BSTR(pvarT) = SysAllocString(L"Example Value Read");
	V_VT(pvarT) = VT_BSTR;
[!crlf]
	// set up the return value to point to the safearray
	V_VT(pVarRead) = VT_ARRAY | VT_VARIANT;
	V_ARRAY(pVarRead) = psa;
	[!crlf]
	return S_OK;
[!endif]
}
[!crlf]

STDMETHODIMP [!ClassName]::ValuesWritten(VARIANT *pVarWritten)
{
[!if=(ScoringComponent,"TRUE")]
    int cEntries = 1;
    // allocate the safearray of VARIANTs
    SAFEARRAY*    psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
    // Populate the safearray variants
    VARIANT* pvarT = (VARIANT*)psa->pvData;
    V_BSTR(pvarT) = SysAllocString(L"_content.score");
    V_VT(pvarT) = VT_BSTR;
    // set up the return value to point to the safearray
    V_VT(pVarWritten) = VT_ARRAY | VT_VARIANT;
    V_ARRAY(pVarWritten) = psa;
    return S_OK;
[!else]
	// TODO: Add your own values to the array
[!crlf]
	int cEntries = 1;
[!crlf]
	// allocate the safearray of VARIANTs
	SAFEARRAY*	psa = SafeArrayCreateVector(VT_VARIANT, 0, cEntries);
[!crlf]
	// Populate the safearray variants
	VARIANT* pvarT = (VARIANT*)psa->pvData;
	V_BSTR(pvarT) = SysAllocString(L"Example Value Written");
	V_VT(pvarT) = VT_BSTR;
[!crlf]
	// set up the return value to point to the safearray
	V_VT(pVarWritten) = VT_ARRAY | VT_VARIANT;
	V_ARRAY(pVarWritten) = psa;
[!crlf]
	return S_OK;
[!endif]

}
[!crlf]
[!endif]


[!if=(ISpecifyPropertyPages, "TRUE")]
//
// ISpecifyPropertyPages Methods
//

STDMETHODIMP [!ClassName]::GetPages(CAUUID *pPages)
{
	if (NULL == pPages)
		return E_INVALIDARG;

	// TODO: Uncomment out the line below, and add the CLSID of a custom Property Page Control

	/*
	pPages->cElems = 1;
	pPages->pElems = (GUID*)CoTaskMemAlloc(1*sizeof(GUID));

	if(!pPages->pElems){
		pPages->cElems = 0;	return E_OUTOFMEMORY;
	}

	memcpy(pPages->pElems, &CLSID_[!CoClassName]Ppg, sizeof(GUID));
	
	return S_OK;
	*/

	return E_NOTIMPL;
}
[!crlf]
[!endif]
[!if=(IPipelineComponentAdmin,"TRUE")]
//
// IPipelineComponentAdmin
//
STDMETHODIMP [!ClassName]::GetConfigData(IDispatch * * ppDict)
{
	if (ppDict == NULL)
		return E_POINTER;
[!if!(CacheLoader)]
/*
	// The following lines give a sample of how to create a dictionary
	// and populate it with a single string value.
[!endif]
[!crlf]
    // Set our ConnectionString property
	CComQIPtr<IDictionary>	pdictPtr;
	CComBSTR				bstrName = L"ConnectionString";
	CComVariant				varItemData = m_bstrConnStr;
	HRESULT					hr;
[!crlf]
	// Return our ConnectionString property
	pdictPtr.CoCreateInstance(L"Commerce.Dictionary");
	hr = pdictPtr->put_Value(bstrName,varItemData);
	if(FAILED(hr))
	{
		return Error(L"An unknown error occurred writing 'ConnectionString' to the Dictionary.",GUID_NULL,hr);
	}
[!crlf]
	return pdictPtr->QueryInterface(IID_IDispatch, reinterpret_cast<void**> (ppDict));
[!if!(CacheLoader)]
/**/
	return E_NOTIMPL;
[!endif]
}
STDMETHODIMP [!ClassName]::SetConfigData(IDispatch * pDict)
{
[!if!(CacheLoader)]
/*
	// The following lines give a sample of how to read data
	// out of the supplied Dictionary.
[!endif]
    // Set our ConnectionString property
	CComQIPtr<IDictionary>	pdictPtr;
	CComBSTR				bstrName = L"ConnectionString";
	CComVariant				varItemData;
	HRESULT					hr;
[!crlf]
	// Performs implicit QI for the proper interface.
	pdictPtr = pDict;
	hr = pdictPtr->get_Value(bstrName,&varItemData);
	if(FAILED(hr))
	{
		return Error(L"An unknown error occurred reading 'ConnectionString' from the provided Dictionary.",GUID_NULL,hr);
	}
[!crlf]
	ATLASSERT(VT_BSTR == varItemData.vt);
	if (VT_BSTR != varItemData.vt)
	{
		return Error(L"Invalid data type in 'ConnectionString'.", GUID_NULL,E_INVALIDARG);
	}
[!crlf]
	if( wcsicmp(L"",varItemData.bstrVal) != 0)
	{
		m_bstrConnStr = varItemData.bstrVal;
	}
	return S_OK;
[!if!(CacheLoader)]
/**/
	return E_NOTIMPL;
[!endif]
}
[!crlf]
[!endif]

[!if=(CacheLoader,"TRUE")]
CComBSTR [!ClassName]::GetGUIDForTableName()
{
	GUID		guidNew;
	WCHAR		szwBuffer[200];
	CComBSTR	bstrRetVal;
[!crlf]
	guidNew = GUID_NULL;
	::CoCreateGuid(&guidNew);
[!crlf]
	if (GUID_NULL == guidNew)
	{
		bstrRetVal = L"";
		return bstrRetVal;
	}
[!crlf]
	wsprintf(szwBuffer,
			L"%08lX_%04X_%04x_%02X%02X_%02X%02X%02X%02X%02X%02X",
			guidNew.Data1, guidNew.Data2, guidNew.Data3,
			guidNew.Data4[0], guidNew.Data4[1], guidNew.Data4[2], guidNew.Data4[3],
			guidNew.Data4[4], guidNew.Data4[5], guidNew.Data4[6], guidNew.Data4[7]);
	bstrRetVal = szwBuffer;
[!crlf]
	return bstrRetVal;
}
[!crlf]
HRESULT [!ClassName]::CreateFactoryFromQuery(_ADOConnection *pConn, CComBSTR bstrTempTable, IContentListFactory** ppclfFactory)
{
    // First get a recordset from our query and ADO ConnectionString
    CComQIPtr<ADORecordset>	prsRecordSet;
    CComQIPtr<_ADOCommand>	pcmdCommand;
    CComQIPtr<ADOParameters> pParams;
	CComQIPtr<ADOParameter>	pparamCurrParam;
    CComQIPtr<IContentListSchema> pclsSchema;
	CComQIPtr<IContentListFactory> pclfFactory;
	CComVariant				varSchema;
	WCHAR					szwFinalQuery[2000];
	CComBSTR				bstrFinalQuery;
	CComBSTR				bstrQueryFormat;
	CComBSTR				bstrNULL;
	CComBSTR				bstrSchemaColumnName;
	CComVariant				varCurrTime, varRecordsAffected, varNoParam, varNULL;
	HRESULT					hr;
	DATE					dteTime;
    SYSTEMTIME				stTime;
[!crlf]
	// Get the current date/time for use later.
    GetLocalTime(&stTime);
[!crlf]
	if (! SystemTimeToVariantTime(&stTime, &dteTime))
	{
		hr = E_FAIL;
		ATLASSERT(0);
		goto HANDLE_ERROR;
	}
[!crlf]
	varCurrTime.vt = VT_DATE;
	varCurrTime.date = dteTime;
[!crlf]
	memset(szwFinalQuery,0,2000 * sizeof(WCHAR));
[!crlf]
	if (NULL == ppclfFactory)
	{
		hr = E_POINTER;
		ATLASSERT(0);
		goto HANDLE_ERROR;
	}
[!crlf]
	(*ppclfFactory) = NULL;
	if (FAILED(hr = LoadLargeString(bstrQueryFormat,[!IDR_QUERYSTRING])))
	{
		ATLASSERT(0);
		goto HANDLE_ERROR;
	}
[!crlf]
	// Fix up the query string with the temp table name (for both locations 
	// the table name appears in the query).
    wsprintf(szwFinalQuery,bstrQueryFormat, bstrTempTable, bstrTempTable);
	bstrFinalQuery = szwFinalQuery;
[!crlf]
	if (FAILED(hr = pcmdCommand.CoCreateInstance(L"ADODB.Command")))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pcmdCommand->putref_ActiveConnection(pConn)))
		goto HANDLE_ERROR;
[!crlf]
    // Construct a command object with date/time parameters
    if (FAILED(hr = pcmdCommand->put_CommandText(bstrFinalQuery)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pcmdCommand->get_Parameters(&pParams)))
		goto HANDLE_ERROR;
[!crlf]
	if (FAILED(hr = pcmdCommand->CreateParameter(bstrNULL, adDBTimeStamp, adParamInput, 0, varCurrTime, &pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pParams->Append(pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
	pparamCurrParam.Release();
[!crlf]
 	if (FAILED(hr = pcmdCommand->CreateParameter(bstrNULL, adDBTimeStamp, adParamInput, 0, varCurrTime, &pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pParams->Append(pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
	pparamCurrParam.Release();
[!crlf]
    // Run the query
    if (FAILED(hr = pcmdCommand->Execute(&varRecordsAffected, &varNoParam, adCmdText, &prsRecordSet)))
		goto HANDLE_ERROR;
[!crlf]
    // Now we need to form a ContentListSchema object describing columnns that we
    // want in the ContentListFactory above and beyond those in the Recordset
	if (FAILED(hr = pclsSchema.CoCreateInstance(L"Commerce.ContentListSchema")))
		goto HANDLE_ERROR;
[!crlf]
    // Like all ContentListFactories used by CSF, we want a column representing
    // the "score" for each content item.  This is private to each ContentList object
    // (as opposed to "public" or "shared" columns where the data lives in the
    //  factory and is shared by all ContentList objects created by that factory)
	bstrSchemaColumnName = L"score";
	if (FAILED(hr = pclsSchema->Add(bstrSchemaColumnName, CLCOL_R4, CLCOL_SCORE_COLUMN + CLCOL_PRIVATE)))
		goto HANDLE_ERROR;
[!crlf]
    // The remaining columns will be public (shared) - the data will live in the
    // factory object and will not be duplicated in each ContentList object
    // created by the factory.
[!crlf]
    // Target_groups is the array of target groups each content item is targeted for
	bstrSchemaColumnName = L"target_groups";
	if (FAILED(hr = pclsSchema->Add(bstrSchemaColumnName, CLCOL_VARIANTARRAY, CLCOL_READONLY)))
		goto HANDLE_ERROR;
[!crlf]
    // PageGroups is the array of page groups each content item is targeted for
	bstrSchemaColumnName = L"pagegroups";
	if (FAILED(hr = pclsSchema->Add(bstrSchemaColumnName, CLCOL_VARIANTARRAY, CLCOL_READONLY)))
		goto HANDLE_ERROR;
[!crlf]
    // Values is a dictionary containing properties specific to each content type
    // (template), e.g. imgUrl, clickUrl, html, text, ASFUrl, etc.
	bstrSchemaColumnName = L"Values";
	if (FAILED(hr = pclsSchema->Add(bstrSchemaColumnName, CLCOL_DISPATCH, CLCOL_READONLY)))
		goto HANDLE_ERROR;
[!crlf]
    // Now we have a recordset and a schema describing columns to add - Create and
    // initialize the factory with this data
	if (FAILED(hr = pclfFactory.CoCreateInstance(L"Commerce.ContentListFactory")))
		goto HANDLE_ERROR;
[!crlf]
	varSchema.vt = VT_DISPATCH;
	pclsSchema->QueryInterface(IID_IDispatch, reinterpret_cast<void**>(&(varSchema.pdispVal)));
	if (FAILED(hr = pclfFactory->ConstructFromRecordset(prsRecordSet, varNULL, varSchema)))
		goto HANDLE_ERROR;
[!crlf]
	hr = pclfFactory.CopyTo(ppclfFactory);
[!crlf]
HANDLE_ERROR:
	return hr;
}
[!crlf]
HRESULT [!ClassName]::LoadLargeString(CComBSTR &bstrToLoad, UINT unID)
{
	USES_CONVERSION;
[!crlf]
	HINSTANCE   hInstResDll = _Module.m_hInstResource;
	HRSRC       hrscReg;
	HGLOBAL     hReg;
	DWORD       dwSize;
	LPSTR       pszaRegA;
	HRESULT		hr = E_FAIL;
[!crlf]
	hrscReg = FindResource(hInstResDll, MAKEINTRESOURCE(unID), L"SQL");
[!crlf]
	if (NULL == hrscReg)
	{
		ATLTRACE(L"Failed to FindResource on ID:%d TYPE:'SQL'\n", 
			unID);
		hr = HRESULT_FROM_WIN32(GetLastError());
		goto ReturnHR;
	}
[!crlf]
	hReg = LoadResource(hInstResDll, hrscReg);
[!crlf]
	if (NULL == hReg)
	{
		ATLTRACE("Failed to LoadResource \n");
		hr = HRESULT_FROM_WIN32(GetLastError());
		goto ReturnHR;
	}
[!crlf]
	dwSize = SizeofResource(hInstResDll, hrscReg);
	pszaRegA = (LPSTR)hReg;
	if (pszaRegA[dwSize] != NULL)
	{
		pszaRegA = (LPSTR)_alloca(dwSize+1);
		memcpy(pszaRegA, (void*)hReg, dwSize+1);
		pszaRegA[dwSize] = NULL;
	}
	bstrToLoad = A2W(pszaRegA);
	hr = S_OK;
[!crlf]
ReturnHR:
	return hr;
}
[!crlf]
HRESULT [!ClassName]::UpdateVDir(_ADOConnection *pConn, IDictionary *pdictOrder)
{
    // Register this application with the virtual_directory table in the campaign DB.
    // This will enable "production refresh" for headlines from the BizDesk using the
    // BDRefresh.asp page in the site.
[!crlf]
    CComQIPtr<ADORecordset>	prsRecordSet;
    CComQIPtr<_ADOCommand>	pcmdCommand;
    CComQIPtr<ADOParameters> pParams;
	CComQIPtr<ADOParameter>	pparamCurrParam;
	CComVariant				varCacheName, varAppUrl,
							varRecordsAffected, varNoParam;
	CComBSTR				bstrItemToRetrieve;
	CComBSTR				bstrQuery;
	CComBSTR				bstrNULL;
	HRESULT					hr = E_FAIL;
[!crlf]
    // These values are written into the cache by the CacheManager object
	bstrItemToRetrieve = L"_CacheName";
    if (FAILED(hr = pdictOrder->get_Value(bstrItemToRetrieve, &varCacheName)))
		goto HANDLE_ERROR;
[!crlf]
	bstrItemToRetrieve = L"_AppUrl";
    if (FAILED(hr = pdictOrder->get_Value(bstrItemToRetrieve, &varAppUrl)))
		goto HANDLE_ERROR;
[!crlf]
    // If either of these is unavailable (e.g. not running in IIS), do nothing
	if ((VT_BSTR != varCacheName.vt) ||
		(VT_BSTR != varAppUrl.vt))
	{
		hr = S_OK;
		goto HANDLE_ERROR;
	}
[!crlf]
    // Invoke sp_update_vdir stored procedure using parameterized query.
    bstrQuery = L"{ call sp_update_vdir (?, ?) }";
[!crlf]
 	if (FAILED(hr = pcmdCommand.CoCreateInstance(L"ADODB.Command")))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pcmdCommand->putref_ActiveConnection(pConn)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pcmdCommand->put_CommandText(bstrQuery)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pcmdCommand->get_Parameters(&pParams)))
		goto HANDLE_ERROR;
[!crlf]
	if (FAILED(hr = pcmdCommand->CreateParameter(bstrNULL, adBSTR, adParamInput, wcslen(varAppUrl.bstrVal), varAppUrl, &pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pParams->Append(pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
	pparamCurrParam.Release();
[!crlf]
 	if (FAILED(hr = pcmdCommand->CreateParameter(bstrNULL, adBSTR, adParamInput, wcslen(varCacheName.bstrVal), varCacheName, &pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
    if (FAILED(hr = pParams->Append(pparamCurrParam)))
		goto HANDLE_ERROR;
[!crlf]
	pparamCurrParam.Release();
[!crlf]
    // Run the query
    if (FAILED(hr = pcmdCommand->Execute(&varRecordsAffected, &varNoParam, adExecuteNoRecords, &prsRecordSet)))
		goto HANDLE_ERROR;
[!crlf]
HANDLE_ERROR:
	return hr;
}
[!crlf]
[!endif]
[!if=(IObjectControl,"TRUE")]
STDMETHODIMP [!ClassName]::Activate()
{
	return E_NOTIMPL;
}
[!crlf]
VOID [!ClassName]::Deactivate()
{
	return;
}
[!crlf]
BOOL [!ClassName]::CanBePooled()
{
	return 0;
}
[!crlf]
[!endif]

[!if=(Shipping,"TRUE")]
HRESULT [!ClassName]::QueryForDictionary(IDictionary *pdictParent, const WCHAR *pcszwName, IDictionary **pdictChild)
{
	if (pdictChild == NULL)
		return E_POINTER;
[!crlf]
	HRESULT hRes = S_OK;
	CComBSTR	bstrName;
	CComVariant	varReturnValue;
[!crlf]
	bstrName = pcszwName;
	if (FAILED(hRes = pdictParent->get_Value(bstrName,&varReturnValue)))
		goto HANDLE_ERROR;
[!crlf]
	ATLASSERT(VT_DISPATCH == varReturnValue.vt);
	if (VT_DISPATCH == varReturnValue.vt)
	{
		varReturnValue.pdispVal->QueryInterface(IID_IDictionary,reinterpret_cast<void**>(pdictChild));
	}
	else
	{
		hRes = E_FAIL;
		goto HANDLE_ERROR;
	}
HANDLE_ERROR:
	return hRes;
}
[!crlf]
HRESULT [!ClassName]::QueryForBSTR(IDictionary *pdictParent, const WCHAR *pcszwName, BSTR *bstrReturnVal)
{
	HRESULT hRes = S_OK;
	CComBSTR	bstrName;
	CComVariant	varReturnValue;
	CComBSTR	bstrValue;
[!crlf]
	bstrName = pcszwName;
	if (FAILED(hRes = pdictParent->get_Value(bstrName,&varReturnValue)))
		goto HANDLE_ERROR;
[!crlf]
	ATLASSERT(VT_DISPATCH == varReturnValue.vt);
	if (VT_DISPATCH == varReturnValue.vt)
	{
		bstrValue = varReturnValue.bstrVal;
		bstrValue.CopyTo(bstrReturnVal);
	}
	else
	{
		hRes = E_FAIL;
		goto HANDLE_ERROR;
	}
HANDLE_ERROR:
	return hRes;
}
[!crlf]
HRESULT [!ClassName]::QueryForSimpleList(IDictionary *pdictParent, const WCHAR *pcszwName, ISimpleList **pslChild)
{
	if (pslChild == NULL)
		return E_POINTER;
[!crlf]
	HRESULT hRes = S_OK;
	CComBSTR	bstrName;
	CComVariant	varReturnValue;
[!crlf]
	bstrName = pcszwName;
	if (FAILED(hRes = pdictParent->get_Value(bstrName,&varReturnValue)))
		goto HANDLE_ERROR;
[!crlf]
	ATLASSERT(VT_DISPATCH == varReturnValue.vt);
	if (VT_DISPATCH == varReturnValue.vt)
	{
		varReturnValue.pdispVal->QueryInterface(IID_ISimpleList,reinterpret_cast<void**>(pslChild));
	}
	else
	{
		hRes = E_FAIL;
		goto HANDLE_ERROR;
	}
HANDLE_ERROR:
	return hRes;
}
[!crlf]
[!endif]